<template>
  <div class>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button v-if="draggable" type="primary" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      node-key="catId"
      show-checkbox
      :expand-on-click-node="false"
      :props="defaultProps"
      :default-expanded-keys="expandedKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref = "categoryTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
            >Append</el-button
          >
          <el-button type="text" size="mini" @click="() => edit(data)"
            >Edit</el-button
          >
          <el-button
            v-if="node.childNodes.length === 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
            >Delete</el-button
          >
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="category"
      >
        <el-form-item label="分类名称">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="category.sort"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: 'product_category',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      pCids: [],
      draggable: false,
      title: '',
      dialogType: '',
      labelPosition: 'right',
      category: {
        name: '',
        parentCid: '',
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: '',
        icon: ''
      },
      dialogVisible: false,
      expandedKeys: [],
      menus: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      updateNodes: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    /**
     * 批量保存
     */
    batchSave () {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '菜单顺序等修改成功',
            type: 'success',
            duration: 500,
            onClose: () => {
              this.updateNodes = []
              this.getMenus()
              this.expandedKeys = this.pCids
              this.pCids = []
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    /**
     * 拖拽结束
     */
    handleDrop (draggingNode, dropNode, dropType, ev) {
      // 获取当前节点最新的父节点id
      console.log(draggingNode, dropNode, dropType)
      let pCid = 0
      let siblings = null
      let level = null
      if (dropType === 'before' || dropType === 'after') {
        if (dropNode.level === 1) {
          pCid = 0
          level = 1
        } else {
          pCid = dropNode.parent.data.catId
          level = dropNode.level
        }
        siblings = dropNode.parent.childNodes
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
        level = dropNode.level + 1
      }
      console.log('当前节点的应该层级:', level)
      console.log(pCid)
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId === draggingNode.data.catId) {
          // 当前节点的层级发生了变化
          if (level !== draggingNode.level) {
            this.updateNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: pCid, catLevel: siblings[i].level})
            this.updateChildNodeLevel(siblings[i])
          } else {
            this.updateNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: pCid})
          }
        } else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i})
        }
      }
      console.log(this.updateNodes)
      this.pCids.push(pCid)
      // this.$http({
      //   url: this.$http.adornUrl('/product/category/update/sort'),
      //   method: 'post',
      //   data: this.$http.adornData(this.updateNodes, false)
      // }).then(({ data }) => {
      //   if (data && data.code === 0) {
      //     this.$message({
      //       message: '菜单顺序等修改成功',
      //       type: 'success',
      //       duration: 500,
      //       onClose: () => {
      //         this.updateNodes = []
      //         this.getMenus()
      //         this.expandedKeys = [pCid]
      //       }
      //     })
      //   } else {
      //     this.$message.error(data.msg)
      //   }
      // })
    },
    updateChildNodeLevel (node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          let cNode = node.childNodes[i].data
          this.updateNodes.push({catId: cNode.catId, catLevel: node.childNodes[i].level})
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },
    /**
     *是否能拖拽到目标节点
     */
    allowDrop (draggingNode, dropNode, type) {
      // 1被拖动节点的当前节点以及所在的父节点总层数不能大于3
      // 1)被拖拽的当前节点的总层数
      const deep = this.countNodeLevel(draggingNode)
      console.log('----------------------------', deep)
      // // let deep = this.maxLevel - draggingNode.data.catLevel * 1 + 1
      // let deep = maxLevel - draggingNode.data.catLevel * 1 + 1
      // console.log(maxLevel, '--', draggingNode.data.catLevel * 1)
      // console.log(deep)
      // // 如果type === inner
      if (type === 'inner') {
        return deep + dropNode.level * 1 <= 3
      } else {
        return deep + dropNode.level * 1 - 1 <= 3
      }
    },
    countNodeLevel (node) {
      let max = 0
      function each (data, floor) {
        data.forEach(e => {
          e.floor = floor
          if (floor > max) {
            max = floor
          }
          if (e.childNodes.length > 0) {
            each(e.childNodes, floor + 1)
          }
        })
      }
      if (node.childNodes.length === 0) {
        return 1
      }
      each(node.childNodes, 2)
      return max
    },
    submitData () {
      if (this.dialogType === 'add') {
        this.addCategory()
      } else if (this.dialogType === 'edit') {
        this.editCategory()
      }
    },
    edit (data) {
      this.title = '修改分类'
      this.dialogVisible = true
      this.dialogType = 'edit'
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        this.category.name = data.category.name
        this.category.catId = data.category.catId
        this.category.icon = data.category.icon
        this.category.productUnit = data.category.productUnit
        this.category.parentCid = data.category.parentCid
        this.category.sort = data.category.sort
        console.log(this.category, '----')
      })
    },
    handleClose (done) {
      done()
    },
    append (data) {
      this.title = '添加分类'
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      this.category.catId = null
      this.category.icon = ''
      this.category.productUnit = ''
      this.category.sort = 0
      this.category.name = ''
      this.category.showStatus = 1
      this.dialogVisible = true
      this.dialogType = 'add'
    },
    addCategory () {
      console.log('提交的三级分类数据', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 500,
            onClose: () => {
              this.dialogVisible = false
              this.getMenus()
              this.expandedKeys = [this.category.parentCid]
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    editCategory () {
      const { catId, name, icon, productUnit, sort } = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData(
          { catId, name, icon, productUnit, sort },
          false
        )
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 500,
            onClose: () => {
              this.dialogVisible = false
              this.getMenus()
              // 展示父菜单
              this.expandedKeys = [this.category.parentCid]
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    batchDelete () {
      const selectKeys = this.$refs.categoryTree.getCheckedKeys()
      this.$confirm(
        `确定进行[${
          selectKeys.length === 1 ? '删除' : '批量删除'
        }]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(selectKeys, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getMenus()
                  console.log('---------------------------------------ednd  ')
                  this.expandedKeys = []
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    },
    remove (node, data) {
      const ids = [data.catId]
      this.$confirm(
        `确定对[${data.name}]进行[${
          ids.length === 1 ? '删除' : '批量删除'
        }]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getMenus()
                  console.log('---------------------------------------ednd  ')
                  this.expandedKeys = [node.parent.data.catId]
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    },
    handleNodeClick (data) {
      console.log(data)
    },
    getMenus () {
      console.log('发送请求。。。')
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        this.menus = data.data
      })
    }

  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getMenus()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  // 生命周期 - 创建之前
  beforeCreate () {},
  // 生命周期 - 挂载之前
  beforeMount () {},
  // 生命周期 - 更新之前
  beforeUpdate () {},
  // 生命周期 - 更新之后
  updated () {},
  // 生命周期 - 销毁之前
  beforeDestroy () {},
  // 生命周期 - 销毁完成
  destroyed () {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated () {}
}
</script>
<style scoped></style>
